import fs from 'fs'
import path from 'path'
import os from 'os'

// 获取组件名列表
export function getComponentName() {
  const arr = [];
  const compStr = fs.readFileSync(path.resolve(process.cwd(), 'component/index.ts')).toString();
  let compArr = compStr.match(/\{[^}]+\}/gm);
  for (let i = 0; i < compArr.length; i += 1) {
    arr.push(compArr[i].slice(1, -1).split(' as ')[1].trim());
  }
  return arr
}

// 获取组件路径列表
export function getComponentPath() {
  const arr = [];
  const compStr = fs.readFileSync(path.resolve(process.cwd(), 'component/index.ts')).toString();
  let compArr = compStr.match(/from\s+(.)+/gm);
  for (let i = 0; i < compArr.length; i += 1) {
    arr.push(compArr[i].replace(/(from\s+|')/g, ''));
  }
  return arr
}

// 获取设备IPv4地址
export function getIPv4Address() {
  const interfaces = os.networkInterfaces();
  if (interfaces.WLAN) { // 有无线网直接获取
    return getIp({ WLAN: interfaces.WLAN })
  }
  return getIp(interfaces)
}

function getIp(interfaces) {
  for (const key in interfaces) { // 没有就获取到第一个地址
    const ips = interfaces[key];
    for (let i = 0; i < ips.length; i += 1) {
      var ipConfig = ips[i];
      if (ipConfig.family === 'IPv4' && ipConfig.address !== '127.0.0.1' && !ipConfig.internal) {
        return ipConfig.address;
      }
    }
  }
}